
L.PenTool = L.Tool.extend({

  enable: function(editor){
    L.Tool.prototype.enable.call(this, editor);
    this.name = "pen_tool";
    // Drawing state
    this._drawing = false;
    this._c = null;
    this._points = null;
    this._apoints = [];
  },

  onDragstartElement: function(element, event){},
  onDragmoveElement: function(element, event){},
  onDragendElement: function(element, event){},

  onDragstartCanvas: function(canvas, event){
    this._drawing = true;
    var pos = canvas.getPos(event);

    this._points = "M" + pos.x + "," + pos.y;
    this._apoints.push(pos);

    this._c = canvas.getRaphael().path();

    this._c.attr({ 
      stroke: this._options.color(),
      "stroke-opacity": this._options.opacity(),
      "stroke-width": this._options.width(),
      "stroke-linecap": "round",
      "stroke-linejoin": "round"
    });
  },
  
  onDragmoveCanvas: function(canvas, event){
    var self = this;  
    setTimeout(function(){
      if (self._drawing == true) {
        var start = Date.now();
        var pos = canvas.getPos(event);
        self._points += "L";
        self._points += pos.x; 
        self._points += ",";
        self._points += pos.y;
        self._apoints.push(pos);
        self._c.node.setAttribute("d", self._points);
      }
    },0);

  },
  onDragendCanvas: function(canvas, event){
    var self = this;
    var path = null;

    
    if (this._c != null) {
      if (this._points.indexOf('L') < 0) {
        this._c.remove();
      } else {
        var path = this._c; 
        var apoints = this._apoints;
        var width = this._options.width();
        setTimeout(function(){
          var points = smoothPath(apoints);
          path.attr({ path: points});
          // fix stroke width; the visible width is
          // scaled along the editor, but viewers 
          // should render the intended width
          path.attrs["stroke-width"] = width;

          //console.log('apoints'); console.log(apoints);
          //console.log('points'); console.log(points);

          var attrs = path.attr();
          attrs.path = points;
          attrs.type = path.type;
          attrs.logical_type = "path";
            //console.log("attrs: type"+attrs.type);
            //console.log(attrs);
          path.remove();
          attrs.layer = self._layer;
          var penElement = new L.Element(attrs);
          canvas.addElement(penElement);
          console.log("penElement");
          console.log(penElement);
        }, 0);
      }
    }
    
    this._drawing = false;
    this._c = null;
    this._points = null;
    this._apoints = [];    
  },

  disable: function(editor){},


});